﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using WalkingTec.Mvvm.Core;

namespace Digitalmes.Services.Tenant
{

    public class TenantConnection
    {
        public string TenantId { get; set; }
        public string WriteConnection { get; set; }
        public string ReadConnection { get; set; }
        public DBTypeEnum DbType { get; set; } = DBTypeEnum.SqlServer;

        public CS ToCS(bool isRead) => new CS
        {
            Key = TenantId,
            Value = isRead ? ReadConnection :WriteConnection, // 默认写连接
            DbType = DbType
        };
    }
    public class TenantProvider : ITenantProvider,ITransient
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IConfiguration _configuration;
        private string _currentTenant;

        public TenantProvider(
            IHttpContextAccessor httpContextAccessor,
            IConfiguration configuration)
        {
            _httpContextAccessor = httpContextAccessor;
            _configuration = configuration;

            // 从请求中自动解析租户 (如 Header/Cookie/Route)
            var tenant = _httpContextAccessor.HttpContext?.Request.Headers["Tenant"].FirstOrDefault();
            _currentTenant = tenant ?? "Default";
        }

        public void SetTenant(string tenantId) => _currentTenant = tenantId;

        public CS GetTenantDbConnection()
        {
            var tenantConfig = _configuration.GetSection("TenantConnections")
                .Get<List<TenantConnection>>()
                .FirstOrDefault(t => t.TenantId == _currentTenant);

            return tenantConfig?.ToCS(_isReadOperation) ?? throw new Exception($"Connection for tenant {_currentTenant} not found");
        }


        // 添加读写状态
        private bool _isReadOperation;

        public void SetReadOperation(bool isRead) => _isReadOperation = isRead;

       
    }
}
